using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RabbitTraceability.Api.Applications.Command;

namespace RabbitTraceability.Api.Applications.CommandHandler
{
    /// <summary>
    /// 添加溯源信息命令处理程序
    /// </summary>
    public class AddTraceabilityInfoCommandHandler : IRequestHandler<AddTraceabilityInfoCommand, string>
    {
        /// <summary>
        /// 溯源仓储
        /// </summary>
        private readonly IRepository<TraceabilityInfo> _repository;
        
        /// <summary>
        /// 对象映射器
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">溯源信息仓储</param>
        /// <param name="mapper">对象映射器</param>
        public AddTraceabilityInfoCommandHandler(IRepository<TraceabilityInfo> repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理添加溯源信息命令
        /// </summary>
        /// <param name="request">添加溯源信息命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>新添加的溯源信息ID</returns>
        public async Task<string> Handle(AddTraceabilityInfoCommand request, CancellationToken cancellationToken)
        {
            // 验证批次号唯一性
            var existingBatch = await _repository.GetAll()
                .AnyAsync(t => t.ProductionBatch == request.ProductionBatch, cancellationToken);
            
            if (existingBatch)
            {
                throw new ApiException(ResultCode.DuplicateProductionBatch, "生产批次号已存在");
            }

            // 使用AutoMapper创建溯源信息实体
            var traceabilityInfo = _mapper.Map<TraceabilityInfo>(request);

            // 添加到数据库
            await _repository.Add(traceabilityInfo);

            // 返回新创建的溯源信息ID
            return traceabilityInfo.TraceabilityId;
        }
    }
} 